/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kedacom.demo.sigar.cloudify;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hyperic.sigar.ProcExe;
import org.hyperic.sigar.ProcState;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

/**
 *
 * @author xiaojinghai
 */
public class DefaultProcessKillerTest {

    public static void main(String args[]) throws SigarException {
        final Sigar sigar = new Sigar();
        final long[] allPids = sigar.getProcList();
        final long myPid = sigar.getPid();

        final Set<Long> childPids = new HashSet<Long>();
        for (final long pid : allPids) {
            try {
                final ProcState state = sigar.getProcState(pid);
                final long ppid = state.getPpid();

                if (ppid == myPid) {
                    System.out.println("Found a leaking process: " + pid);
                    childPids.add(pid);
                }
            }
            catch (final SigarException e) {
                // probably means that the process belongs to another user to may not have permissions
                // to read its data. Should be safe to ignore
            }
        }

        if (!childPids.isEmpty()) {
            System.out.println("Warning: found leaked processes after test finished: " + childPids);
            final DefaultProcessKiller killer = new DefaultProcessKiller();
            for (final Long pid : childPids) {
                final ProcExe procExe = sigar.getProcExe(pid);
                final String[] procArgs = sigar.getProcArgs(pid);
                System.out.println("Killing process: " + pid + ". Name: " + procExe.getName() + ", Args: "
                        + Arrays.toString(procArgs) + "Directory: " + procExe.getCwd());
                try {
                    killer.killProcess(pid);
                }
                catch (final USMException e) {
                    System.out.println("Failed to kill process: " + pid);
                }

            }

        }
    }
}
